#!/bin/bash
#==============================================================#
# File      :   create-pub
# Desc      :   Create publication on src cluster
# Time      :   {{ '%Y-%m-%d %H:%M' |strftime }}
# Path      :   {{ dir_path }}/create-pub
# Deps      :   bash
# License   :   AGPLv3 @ https://doc.pgsty.com/about/license
# Copyright :   2018-2025  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#


#--------------------------------------------------------------#
# Utils
#--------------------------------------------------------------#
__CN='\033[0m';__CB='\033[0;30m';__CR='\033[0;31m';__CG='\033[0;32m';
__CY='\033[0;33m';__CB='\033[0;34m';__CM='\033[0;35m';__CC='\033[0;36m';__CW='\033[0;37m';
function log_info() {  printf "[${__CG} OK ${__CN}] ${__CG}$*${__CN}\n";   }
function log_warn() {  printf "[${__CY}WARN${__CN}] ${__CY}$*${__CN}\n";   }
function log_error() { printf "[${__CR}FAIL${__CN}] ${__CR}$*${__CN}\n";   }
function log_debug() { printf "[${__CB}HINT${__CN}] ${__CB}$*${__CN}\n"; }
function log_input() { printf "[${__CM} IN ${__CN}] ${__CM}$*\n=> ${__CN}"; }
function log_hint()  { printf "${__CB}$*${__CN}\n"; }
function log_line()  { printf "${__CM}[$*] ===========================================${__CN}\n"; }


#--------------------------------------------------------------#
# Param
#--------------------------------------------------------------#
# check if MIGRATION_CONTEXT is defined as expected
EXPECTED_CONTEXT="{{ src_cls }}.{{ src_db }}"
if [[ "${MIGRATION_CONTEXT}" != "${EXPECTED_CONTEXT}" ]]; then
    log_error "MIGRATION_CONTEXT = ${MIGRATION_CONTEXT} != EXPECTED ${EXPECTED_CONTEXT}"
    log_hint "did you run . activate first?"
    exit 1
fi
SQLFILE="data/create-pub.sql"


#--------------------------------------------------------------#
# Planning
#--------------------------------------------------------------#
log_info "generate create publication sql on ${SQLFILE}"

echo 'CREATE PUBLICATION "'"${PUBNAME}"'" FOR TABLE' > ${SQLFILE}
psql "${SRCPG}" -qAXtw >> "${SQLFILE}" <<-EOF

SELECT string_agg(name, E',\n') || ';' AS sql FROM
    (SELECT quote_ident(nspname) || '.' || quote_ident(relname) AS name FROM pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid
     WHERE relkind = 'r' AND relname != 'spatial_ref_sys'
       AND nspname !~ '^pg_' AND nspname !~ '^_' AND nspname !~ '^timescaledb' AND nspname !~ '^citus' AND nspname !~ '^columnar'
       AND nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'repack', 'monitor')) tbl;

EOF

# print sql
cat ${SQLFILE}


#--------------------------------------------------------------#
# Asking
#--------------------------------------------------------------#
log_input "create publication on src ? (yes/no) >"
read -r
case ${REPLY} in
    [yY][eE][sS]|[yY])
        log_info   "create publication on: ${SRCCLS}.${SRCDB}"
        log_info   "  - SRC URL  : ${SRCPG}"
        log_info   "  - SQL FILE : ${SQLFILE}"
        log_debug  "$ psql '${SRCPG}' -Xwf ${SQLFILE}"
        psql "${SRCPG}" -Xwf ${SQLFILE}
        exit 0
        ;;
    *)
        log_info  "you can exam it and create pub later with:"
        log_debug  "$ psql '${SRCPG}' -Xwf ${SQLFILE}"
        exit 1
        ;;
esac